import hashlib
import json
import logging
import time
import urllib

import requests


class JikeYunAPI:
    """
    吉客云开放平台API客户端
    """

    def __init__(self, app_key, app_secret):
        """
        初始化API客户端
        :param app_key: 应用的AppKey
        :param app_secret: 应用的AppSecret
        """
        self.app_key = app_key
        self.app_secret = app_secret
        self.api_url = "https://open.jackyun.com/open/openapi/do"

    def send_request(self, method, bizdata):
        """
        向吉客云开放平台发送API请求。
        :param method: API接口名称
        :param bizdata: 业务请求参数（JSON格式字符串）
        :return: API响应
        """
        # 1. 准备用于签名的系统级参数
        # 将bizdata转换为JSON字符串
        bizcontent_str = json.dumps(bizdata, ensure_ascii=False) if isinstance(bizdata, dict) else str(bizdata)
        params_for_sign = {
            'method': method,
            'appkey': self.app_key,
            'version': '1.0',
            'contenttype': 'json',
            'timestamp': time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
            'bizcontent': bizcontent_str
        }
        # 2. 生成签名
        sorted_params = sorted(params_for_sign.items())
        query_string = ""
        for key, value in sorted_params:
            if key and value:
                query_string += f"{key}{value}"
        sign_string = (self.app_secret + query_string + self.app_secret).lower()
        signature = hashlib.md5(sign_string.encode('utf-8')).hexdigest().lower()
        # 3. 准备最终请求体
        post_data_parts = []
        # 将签名加入到参数中
        params_for_sign['sign'] = signature
        for key, value in params_for_sign.items():
            if key == 'bizcontent':
                # 只对bizcontent进行URL编码
                post_data_parts.append(f"{key}={urllib.parse.quote(str(value), safe='')}")
            else:
                post_data_parts.append(f"{key}={str(value)}")

        post_data_str = "&".join(post_data_parts)
        # 4. 发送POST请求
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
        }
        try:
            response = requests.post(self.api_url, data=post_data_str.encode('utf-8'), headers=headers)
            response.raise_for_status()
            # 解析响应
            api_response = response.json()
            try:
                logging.info(f"吉客云API原始响应: {api_response}")
            except (IOError, OSError) as log_error:
                # 日志记录失败，记录到标准错误输出
                print(f"警告：日志记录失败 - {log_error}")
            return api_response

        except requests.exceptions.Timeout:
            print("请求超时")
            return {
                'success': False,
                'code': 'TIMEOUT',
                'message': '请求超时，请稍后重试'
            }
        except requests.exceptions.ConnectionError:
            print("网络连接错误")
            return {
                'success': False,
                'code': 'CONNECTION_ERROR',
                'message': '网络连接失败，请检查网络设置'
            }
        except requests.exceptions.HTTPError as e:
            print(f"HTTP错误: {e}")
            return {
                'success': False,
                'code': f'HTTP_{e.response.status_code}',
                'message': f'HTTP错误: {e.response.status_code}'
            }
        except json.JSONDecodeError:
            print("响应不是有效的JSON格式")
            return {
                'success': False,
                'code': 'INVALID_JSON',
                'message': '服务器响应格式错误'
            }
        except requests.exceptions.RequestException as e:
            print(f"请求出错: {e}")
            return {
                'success': False,
                'code': 'REQUEST_ERROR',
                'message': f'请求失败: {str(e)}'
            }
        except Exception as e:
            logging.error(f"未知错误: {e}")
            return {
                'success': False,
                'code': 'UNKNOWN_ERROR',
                'message': f'未知错误: {str(e)}'
            }

    def batch_update_flag_by_sku_barcode(self, items):
        """
        批量更新商品标签
        :param items: 商品标签数据列表，格式: [{"flagDataName":"标签名","skuBarcode":"商品条码"}]
        :return: API响应
        """
        # 记录外部传入的items参数
        logging.info(f"批量更新商品标签 - 外部传入的items参数: {items}")
        method = 'erp-goods.goods.batchupdateflagbyskubarcode'
        return self.send_request(method, items)


# 为了保持向后兼容性，保留原有的函数接口
def send_request(app_key, app_secret, method, bizdata):
    """
    向吉客云开放平台发送API请求（兼容性函数）
    :param app_key: 应用的AppKey
    :param app_secret: 应用的AppSecret
    :param method: API接口名称
    :param bizdata: 业务请求参数
    :return: API响应
    """
    api_client = JikeYunAPI(app_key, app_secret)
    return api_client.send_request(method, bizdata)


if __name__ == '__main__':

    app_key = 'YOUR_APP_KEY'
    app_secret = 'YOUR_APP_SECRET'

    # 创建API客户端
    api_client = JikeYunAPI(app_key, app_secret)

    # 准备商品标签数据
    items = [{"flagDataName": "淘汰品", "skuBarcode": "34215678"}]

    # 2. 发送请求
    response = api_client.batch_update_flag_by_sku_barcode(items)

    # 3. 处理响应
    print(f"API响应: {response}")
    if response.get('code') == 200 and response.get('result', {}).get('data') is not None:
        print("请求成功")
        print(f"返回数据: {response.get('result', {}).get('data')}")
    else:
        error_msg = response.get('msg', '未知错误')
        sub_code = response.get('subCode', '')
        print(f"请求失败: {error_msg} (错误码: {sub_code})")
